import { Promise } from 'core-js'
import Vue from 'vue'
import Vuex from 'vuex'
import socket from '../socket'

Vue.use(Vuex)

const state = {
  nickname:'',//当前用户昵称，
  nicknames:[],//房间用户列表
  holder:'',//游戏主持
  lines:[],//房间绘图信息(记录画了多少跟线，怎么画的)
  connected:false,//连接状态
}

const mutations = {
  updateNickname(state,nickname){
    state.nickname = nickname || ''
  },
  updateNicknames(state,nicknames){
    state.nicknames=nicknames || []
  },
  updateHolder(state,holder){
    state.holder=holder || ''
  },
  updateLines(state,lines){
    state.lines = lines||[]
  },
  //将新人追加到列表中去
  addToNicknames(state,nickname){
    //用户不存在才追加
    if (!state.nicknames.includes(nickname)) {
    state.nicknames.push(nickname)
      
    }
  },updateConnected(state,falg){
    state.connected = falg
  },

  //画新线
  drawNewLine(state,newLine){
      state.lines.push(newLine)
  },
  //鼠标滑动更新线
  updateNewLine(state,lastline){

    const line = state.lines[state.lines.length-1]
    line.points = lastline.points

  },
  delFromNicknames(state,nickname){

    state.nicknames = state.nicknames.filter(item=>item !=nickname)

  }
}

const actions = {
  //确认昵称是否占用
  checkUserExist(context,nickname){
    return new Promise((resolve,reject)=>{
      socket.emit('check_user_exist',nickname,isExist=>{
        resolve(isExist)
      })
    })
  },
  sendUserEnter(context){
    const nickname=localStorage.getItem('nickname')
    socket.emit('enter',nickname)
    context.commit('updateNickname', nickname);
  },
  
  //告诉服务器，申请主持人
  sendStartGame(context,answer){
    socket.emit('start_game',answer)

  },


  //终止游戏
  sendStopGame(context){
    socket.emit('stop_game')
  },
  updateNewLine(context,line){

    socket.emit('new_line',line)


  },
  sendUpdateNewLine(context,line){
    socket.emit('update_line',line)

  },
  sendAnswerGame(context,inputImageName){
    socket.emit('answer_game',inputImageName)
  },
  sendUserLeave(context){
      //发送退出的消息
      socket.emit('leave')
      //都退出了，应该重置本低昵称
      context.commit('updateNickname','')
      localStorage.removeItem('nickname')
  }
}

const getters = {
  isGameStarted(){
    if(state.holder){
      return true
    }else{
      return false
    }
  },
  isGameHolder(state){

    return state.nickname === state.holder

  }
}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})
